/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.ipo.mm.web.util;

import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionForward;

/**
 *
 * @author makcro
 */
public class BreadCrumbs {

    ArrayList<BreadCrumbPair> stack = new ArrayList<BreadCrumbPair>();
    private BreadCrumbPair defaultBC = null;
    private final String defaultBCName = "Main page";

    public BreadCrumbs() {
        String url = "/protected/dispatch.do?method=showMainPage";
        ActionForward forward = new ActionForward(url, false);
        defaultBC = new BreadCrumbPair(defaultBCName, forward);
    }

    public void push(String name, ActionForward actionForward) {
        push(new BreadCrumbPair(name, actionForward));
    }

    public void push(BreadCrumbPair breadCrumbPair) {
        if (stack.isEmpty()) {
            stack.add(breadCrumbPair);
        }
        else {
            BreadCrumbPair top = stack.get(stack.size() - 1);
            if (!top.equals(breadCrumbPair)) {
                stack.add(breadCrumbPair);
            }

        }


    }

    public BreadCrumbPair pop() {
        if (!stack.isEmpty()) {
            BreadCrumbPair top = stack.get(stack.size() - 1);
            stack.remove(top);
            return top;
        } else {
            return defaultBC;
        }

    }

    public void clearStack() {
        stack.clear();
    }

    public ArrayList<BreadCrumbPair> getAll() {
        return (ArrayList<BreadCrumbPair>) stack.clone();
    }

    public void push(String name, HttpServletRequest request) {
        String clearStack = request.getParameter("clearStack");

        if (clearStack != null) {
            clearStack();
        }
        String url = request.getRequestURI() + "?" + request.getQueryString();
        url = url.substring(url.indexOf("/", url.indexOf("/") + 1));
        ActionForward f = new ActionForward(url, false);

        push(name, f);
        request.getSession().setAttribute("title", name);
    }
}
